package com.example.seakdreamandroid.accountInfo;

import static com.example.seakdreamandroid.Constant.BASE_URL;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.LoginActivity;
import com.example.seakdreamandroid.MemberActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.User;
import com.yalantis.ucrop.UCrop;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//何鸿辉
public class AccountInfoActivity extends AppCompatActivity {
    //控件
    private ImageView imgReturn;
    private ImageView imgHeadShort;
    private RelativeLayout nickName;
    private TextView txNickName;
    private RelativeLayout sex;
    private TextView txSex;
    private RelativeLayout birthday;
    private TextView txBirthday;
    private RelativeLayout location;
    private TextView txLocation;
    private RelativeLayout phone;
    private TextView txPhone;
    private LinearLayout introduction;
    private TextView txIntroduction;
    private Button exit;

    //记录系统相机拍摄的照片的uri
    private Uri mUri;
    private User user;



    //暂停页面的弹窗
    PopupAndDarkenWindow loadingPopup;
    //点击头像弹出的弹窗
    PopupAndDarkenWindow headShortPopup;
    //修改性别弹出的弹窗
    PopupAndDarkenWindow sexPopup;
    //修改生日的弹窗
    PopupAndDarkenWindow birthPopup;
    //修改地址的弹窗


    //常量
    //图片类型
    private final String IMAGE_TYPE = "image/*";
    private static final String TAG = "AccountInfoActivity";
    //打开相册选择图片的请求码
    public static final int IMAGE_PICK_REQUEST_CODE = 1;
    //请求相机权限的请求码
    private static final int MY_PERMISSIONS_REQUEST_CODE = 2;
    //请求系统相机拍照的请求码
    private static final int CAMERA_REQUEST_CODE = 3;
    //修改昵称跳转界面时候的请求码
    public static final int EDIT_NICKNAME_REQUEST_CODE = 4;
    //修改地址跳转界面时候的请求码
    public static final int EDIT_LOCATION_REQUEST_CODE = 5;
    //修改手机号跳转界面时候的请求码
    public static final int EDIT_PHONE_REQUEST_CODE = 6;
    //修改简介跳转界面时候的请求码
    public static final int EDIT_INTRODUCTION_REQUEST_CODE = 7;
    //系统相机拍摄的照片在共享目录中的文件名
    private static final String IMAGE_FROM_CAMERA_FILE_NAME = "temp.png";
    private static final int FAILURE = 1;
    private static final int OK = 2;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_info);
        user = (User)getApplicationContext();
        getViews();
        setListener();
        initALlPopupAndDarkenWindow();
        setDataToView();

    }

    private void setDataToView() {
        String userId = user.getUserId();
        Log.i(TAG,"setDataToView-userId=" + userId);
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+userId)
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e(TAG,"请求数据失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                        loadingPopup.dismiss();
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                Log.i(TAG,"setDataToView-onResponse"+"成功");
                try {
                    String resultStr = response.body().string();
                    Log.i(TAG,"setDataToView-resultStr" + resultStr);
                    JSONObject object = new JSONObject(resultStr);
                    JSONObject data = object.getJSONObject("data");
                    if(!data.isNull("headshot")) {
                        String headshot1 = data.getString("headshot");
                        byte[] bs = Base64.decode(headshot1, Base64.DEFAULT);
                        for (int i = 0; i < bs.length; ++i) {
                            if (bs[i] < 0) {
                                bs[i] += 256;
                            }
                        }
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Glide.with(AccountInfoActivity.this).load(bitmap).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(imgHeadShort);
                            }
                        });
                    }
                    if(!data.isNull("userName")){
                        String nickname1 = data.getString("userName");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txNickName.setText(nickname1);
                            }
                        });
                    }
                    if(!data.isNull("birthday")){
                        String birthday = data.getString("birthday");
                        Log.i(TAG,"birthday="+data.isNull("birthday"));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txBirthday.setText(birthday);
                            }
                        });
                    }
                    if(!data.isNull("gender")){
                        String sex = data.getString("gender");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txSex.setText(sex);
                            }
                        });
                    }
                    if(!data.isNull("location")){
                        String location = data.getString("location");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txLocation.setText(location);
                            }
                        });
                    }
                    if(!data.isNull("phone")){
                        String phone = data.getString("phone");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txPhone.setText(phone);
                            }
                        });
                    }
                    if(!data.isNull("description")){
                        String description = data.getString("description");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txIntroduction.setText(description);
                            }
                        });
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                //setview
            }
        });

    }

    private void initALlPopupAndDarkenWindow() {
        loadingPopup = new PopupAndDarkenWindow(this,R.layout.loading);
        loadingPopup.setLayoutParam(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        loadingPopup.setPopup(false);
        loadingPopup.setDarken(false);
        loadingPopup.init();

        headShortPopup = new PopupAndDarkenWindow(AccountInfoActivity.this, R.layout.popup_head_short);
        headShortPopup.setPopupViewListener(new PopupAndDarkenWindow.SetPopupViewListenerCallBack() {
            @Override
            public void setListener(View v, PopupAndDarkenWindow popupAndDarkenWindow) {
                Button camera = (Button) v.findViewById(R.id.account_info_camera);
                Button gallery = (Button) v.findViewById(R.id.account_info_gallery);
                Button cancel = (Button) v.findViewById(R.id.account_info_cancel);

                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupAndDarkenWindow.dismiss();
                        //拍照设置头像
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CODE);
                            return;
                        }
                        launchCamera();
                    }

                });
                gallery.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupAndDarkenWindow.dismiss();
                        //从相册中选择图片设置头像
                        Intent intent = new  Intent(Intent.ACTION_PICK);
                        // 指定获取的是图片
                        intent.setType("image/*");
                        startActivityForResult(intent, IMAGE_PICK_REQUEST_CODE);
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupAndDarkenWindow.dismiss();
                    }
                });
            }
        });
        headShortPopup.init();

        sexPopup = new PopupAndDarkenWindow(this,R.layout.popup_sex);
        sexPopup.setPopupViewListener(new PopupAndDarkenWindow.SetPopupViewListenerCallBack() {
            @Override
            public void setListener(View v, PopupAndDarkenWindow popupAndDarkenWindow) {
                Button male = v.findViewById(R.id.male);
                Button female = v.findViewById(R.id.female);
                Button cancel = v.findViewById(R.id.cancel);
                male.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupAndDarkenWindow.dismiss();
                        uploadSex("男");
                    }
                });
                female.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupAndDarkenWindow.dismiss();
                        uploadSex("女");
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupAndDarkenWindow.dismiss();
                    }
                });
            }
        });
        sexPopup.init();

        birthPopup = new PopupAndDarkenWindow(this,R.layout.popup_birthday);
        birthPopup.setPopupViewListener(new PopupAndDarkenWindow.SetPopupViewListenerCallBack() {
            @Override
            public void setListener(View v, PopupAndDarkenWindow popupAndDarkenWindow) {
                DatePicker datePicker = v.findViewById(R.id.date);
                TextView save = v.findViewById(R.id.save);
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupAndDarkenWindow.dismiss();
                        Date date = new Date(datePicker.getYear()-1900,datePicker.getMonth(),datePicker.getDayOfMonth());
                        updateBirthday(date);
                    }
                });
            }
        });
        birthPopup.init();
    }

    private void updateBirthday(Date date){
        String userId = user.getUserId();
        loadingPopup.popupWindow();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + "UserInfo/setBirthday?userId=" + userId + "&birthday=" + format.format(date))
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"onFailure，上传生日失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                        loadingPopup.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txBirthday.setText(format.format(date));
                        loadingPopup.dismiss();
                    }
                });
            }
        });
    }

    private void uploadSex(String sex) {
        String userId = user.getUserId();
        loadingPopup.popupWindow();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + "UserInfo/setSex?userId=" + userId + "&sex=" + sex)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"onFailure，上传性别失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                        loadingPopup.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txSex.setText(sex);
                        loadingPopup.dismiss();
                    }
                });
            }
        });
    }


    private void checkSharedDirection() {
        File dir = new File(getExternalCacheDir() + "/shared");
        if(!dir.exists()){
            dir.mkdir();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case IMAGE_PICK_REQUEST_CODE:
                //选择头像图片返回
                resolveImagePick(resultCode,data);
                break;
            case UCrop.REQUEST_CROP:
                //裁剪成头像返回
                resolveImageResult(resultCode,data);
                break;
            case CAMERA_REQUEST_CODE:
                //使用系统相机拍照获取图片返回
                resolveImageFromCamera(resultCode,data);
            case EDIT_NICKNAME_REQUEST_CODE:
                //修改完昵称返回
                resolveEditNickName(resultCode,data);
                break;
            case EDIT_LOCATION_REQUEST_CODE:
                resolveEditLocation(resultCode,data);
                break;
            case EDIT_INTRODUCTION_REQUEST_CODE:
                resolveEditIntroduction(resultCode,data);
        }
    }

    private void resolveEditIntroduction(int resultCode, Intent data) {
        if(resultCode == RESULT_OK){
            loadingPopup.popupWindow();
            uploadIntroduction(data.getStringExtra("introduction"));
        }
    }

    private void uploadIntroduction(String introduction) {

        String userId = user.getUserId();
        loadingPopup.popupWindow();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + "UserInfo/setDescription?userId=" + userId + "&description=" + introduction)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"onFailure，上传简介失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                        loadingPopup.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txIntroduction.setText(introduction);
                        loadingPopup.dismiss();

                    }
                });
            }
        });
    }

    private void resolveEditLocation(int resultCode, Intent data) {
        if(resultCode == RESULT_OK){
            loadingPopup.popupWindow();
            uploadLocation(data.getStringExtra("info"));
        }
    }

    private void uploadLocation(String location) {
        String userId = user.getUserId();
        loadingPopup.popupWindow();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + "UserInfo/setLocation?userId=" + userId + "&location=" + location)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"onFailure，上传地址失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                        loadingPopup.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txLocation.setText(location);
                        loadingPopup.dismiss();

                    }
                });
            }
        });
    }

    private void resolveEditNickName(int resultCode,Intent data) {
        if(resultCode == RESULT_OK){
            loadingPopup.popupWindow();
            uploadNickName(data.getStringExtra("info"));
        }
    }

    private void uploadNickName(String nickName) {
        String userId = user.getUserId();
        loadingPopup.popupWindow();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(BASE_URL + "UserInfo/setNickName?userId=" + userId + "&nickName=" + nickName)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG,"onFailure，上传昵称失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                        loadingPopup.dismiss();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txNickName.setText(nickName);
                        loadingPopup.dismiss();
                    }
                });
            }
        });
    }

    private void resolveImageFromCamera(int resultCode, Intent data) {
        if(resultCode == RESULT_OK){
            startCrop(mUri);
        }
    }

    private void setListener() {
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountInfoActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
        imgReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AccountInfoActivity.this.finish();
            }
        });
        imgHeadShort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                headShortPopup.popupWindow();
            }
        });
        nickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountInfoActivity.this, InfoEditActivity.class);
                intent.putExtra("requestCode",EDIT_NICKNAME_REQUEST_CODE);
                intent.putExtra("info",txNickName.getText().toString());
                startActivityForResult(intent,EDIT_NICKNAME_REQUEST_CODE);
            }
        });
        sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexPopup.popupWindow();
            }
        });
        birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                birthPopup.popupWindow();
            }
        });
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountInfoActivity.this, InfoEditActivity.class);
                intent.putExtra("requestCode",EDIT_LOCATION_REQUEST_CODE);
                intent.putExtra("info",txLocation.getText());
                startActivityForResult(intent,EDIT_LOCATION_REQUEST_CODE);
            }
        });

        introduction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountInfoActivity.this,IntroductionEditActivity.class);
                intent.putExtra("introduction",txIntroduction.getText());
                startActivityForResult(intent,EDIT_INTRODUCTION_REQUEST_CODE);
            }
        });
    }

    private void getViews() {
        imgReturn = findViewById(R.id.img_return);
        imgHeadShort = findViewById(R.id.img_head_short);
        nickName = findViewById(R.id.nickname);
        txNickName = findViewById(R.id.tx_nickname);
        sex = findViewById(R.id.sex);
        txSex = findViewById(R.id.tx_sex);
        birthday = findViewById(R.id.birthday);
        txBirthday = findViewById(R.id.tx_birthday);
        location = findViewById(R.id.location);
        txLocation = findViewById(R.id.tx_location);
        phone = findViewById(R.id.phone);
        txPhone = findViewById(R.id.tx_phone);
        introduction = findViewById(R.id.introduction);
        txIntroduction = findViewById(R.id.tx_introduction);
        exit = findViewById(R.id.btn_logout);
    }

    private void resolveImagePick(int resultCode, Intent data) {
        if(resultCode == RESULT_OK){
            Uri imageUri = data.getData();
            startCrop(imageUri);
        }
    }

    //开始裁剪
    private void startCrop(Uri sourceUri) {
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), System.currentTimeMillis()+"temp.jpg"));
        UCrop.Options options = new UCrop.Options();
        options.setCircleDimmedLayer(true);
        options.setShowCropFrame(false);
        options.setShowCropGrid(false);
        options.withAspectRatio(1,1);
        UCrop.of(sourceUri, destinationUri).withOptions(options).start(this);

    }



    private void resolveImageResult(int resultCode,Intent data) {
        if (resultCode == RESULT_OK) {
            //将裁剪头像上传到服务器，此时页面处于暂停状态，知道服务器返回结果，如果结果为ok，将头像图片保存到本地，同时头像修改，
            loadingPopup.popupWindow();
            uploadHeadShort(UCrop.getOutput(data));

        }
        //裁切失败
        else if (resultCode == UCrop.RESULT_ERROR) {
            Toast.makeText(this, "哎呀，出错了", Toast.LENGTH_SHORT).show();
        }
    }

    private void uploadHeadShort(Uri imgUri) {
        try {
            loadingPopup.popupWindow();
            File file = new File(imgUri.getPath());
            FileInputStream in = new FileInputStream(file);
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            String res = Base64.encodeToString(data,Base64.DEFAULT);
            FormBody body = new FormBody.Builder()
                    .add("userId",user.getUserId())
                    .add("headshot",res)
                    .build();
            //3.创建请求对象（Request）
            Request request = new Request.Builder()
                    //设置
                    .url(Constant.BASE_URL + "UserInfo"+"/setHeadshot")
                    .post(body)//设置请求方式为POST，添加了请求体
                    //创建Request对象
                    .build();
            //4.发送请求，获取响应
            OkHttpClient okHttpClient = new OkHttpClient();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG,"onFailure，上传头像失败");
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(AccountInfoActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();
                            loadingPopup.dismiss();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(AccountInfoActivity.this).load(imgUri).apply(new RequestOptions().circleCrop()).into(imgHeadShort);
                            System.out.println(imgUri.getPath());
                            loadingPopup.dismiss();

                        }
                    });
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //当请求权限获得结果时
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (MY_PERMISSIONS_REQUEST_CODE == requestCode) {
            //循环遍历已经申请到的权限
            for (int index = 0; index < permissions.length; index++) {
                switch (permissions[index]) {
                    case Manifest.permission.CAMERA:
                        if (PackageManager.PERMISSION_GRANTED == grantResults[index]) {
                            launchCamera();
                        } else if (PackageManager.PERMISSION_DENIED == grantResults[index]) {
                            Toast.makeText(AccountInfoActivity.this, "应用没有拍照权限，请授权！", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(AccountInfoActivity.this, "应用没有拍照权限，请授权", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }

            }

        }
    }


    private void launchCamera() {
        checkSharedDirection();
        String filePath = getExternalCacheDir().getAbsolutePath()+"/shared/" + IMAGE_FROM_CAMERA_FILE_NAME;
        File file = new File(filePath);
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定存储路径,保存原图
        if(Build.VERSION.SDK_INT >=  24){
            mUri = FileProvider.getUriForFile(AccountInfoActivity.this, "com.example.seakdreamandroid.FileProvider", file);
        } else {
            mUri = Uri.fromFile(file);
        }
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);
    }

}